import { debug } from "./log";

let callback = []
function _init(event: string) {
    if (!callback[event]) {
        callback[event] = {
            data: null,
            func: []
        };
    }
}
function _on(event: string, listen: Function) {
    _init(event)

    const unlisten = () => {
        const index = callback[event].func.findIndex(fun => fun == listen);
        if (index > -1) {
            debug('卸载')
            callback[event].func.splice(index, 1)
        }
    }
    const data = callback[event].data
    if (data) {
        listen(data)
    }
    callback[event].func.push(listen)
    return unlisten
}
function _emit(event: string, data: any) {
    _init(event)

    // const item = this.callback[event];
    callback[event].data = data;
    callback[event].func.forEach(callback => {
        callback(data)
    });
}
if (!(window as any).__MICRO_APP_EVENT) {
    (window as any).__MICRO_APP_EVENT = {
        _on,
        _emit
    }
}
export const onGloblState = (window as any).__MICRO_APP_EVENT._on
export const emitGloblState = (window as any).__MICRO_APP_EVENT._emit